#include "SubsystemManager.h"

#include "Misc/StdHead.h"


void RSubsystemManager::InitializeSubsystems(CClass* SubsystemClass,RObject* InOwner)
{
#ifdef DEBUG
    bIsInitializingSubsytems=true;
#endif 
    Owner=InOwner;

    // find all subsystem
    for(CType* SubType: SubsystemClass->DerivedTypes)
    {
        if(!SubType->IsClassType())
        {
            continue;
        }
        CClass* SubClass= reinterpret_cast<CClass*>(SubType);

        if(!Subsystems.Contains(SubClass))
        {
            RSubsystemPtr NewSubsystem=NewObject<RSubsystem>(SubClass,Owner);
            NewSubsystem->Manager=this;
            Subsystems.Add(SubClass,NewSubsystem);

            NewSubsystem->Initialize();
        }
    }

#ifdef DEBUG
    bIsInitializingSubsytems=false;
#endif  
   
    bIsSubsystemInitialized=true;

}

void RSubsystemManager::DeinitializeSubsystems()
{
    assert(bIsSubsystemInitialized && "Cant invoke DeinitializeSubsystems() before InitializeSubsystems()");

    for(auto& SubsystemPair:Subsystems )
    {
        SubsystemPair.Value->Deinitialize();
    }

    //恢复到初始化之前状态
    Subsystems.Clear();
    bIsSubsystemInitialized=false;
}

RSubsystemManager::~RSubsystemManager()
{
    if(bIsSubsystemInitialized)
    {
        DeinitializeSubsystems();
    }
}

